package com.lz.helper

import android.os.Handler
import android.os.Looper
import android.os.Message
import com.lz.helper.face.CameraOperator
import com.lz.helper.face.FeatureRequest
import java.lang.ref.WeakReference

class CameraHelper(w: Int, h: Int, callback: CameraCallback) : Handler(Looper.getMainLooper()), CameraOperator.CameraHandler {

    companion object {
        private const val MSG_DETECT = 1
        private const val MSG_ERR = 2
    }

    //核心处理
    private val operator = CameraOperator(w, h, 5000, this)

    private val reference = WeakReference(callback)

    //线程是否开启
    private var hasStarted = false

    fun start() {
        if (!hasStarted) {
            hasStarted = true
            Thread(operator, "CameraOperator-Thread").start()
        }
    }

    fun restart() {
        if (hasStarted) operator.restart()
    }

    fun pause() {
        operator.pause()
    }

    fun quit() {
        operator.quit()
    }

    fun pushNvData(nvData: ByteArray) {
        operator.pushNvData(nvData)
    }

    fun pushFeatureRequest(request: FeatureRequest): Boolean = operator.pushFeatureRequest(request)

    override fun sendDetectSuccess(detect: IntArray) {
        sendMessage(obtainMessage(MSG_DETECT, detect))
    }

    override fun sendError(status: Int) {
        sendMessage(obtainMessage(MSG_ERR, status, 0))
    }

    override fun handleMessage(msg: Message) {
        when(msg.what) {
            MSG_ERR -> reference.get()?.onCameraError(msg.arg1)
            MSG_DETECT -> reference.get()?.onDetectSuccess(msg.obj as IntArray)
        }
    }

    interface CameraCallback {

        //检测轮廓成功
        fun onDetectSuccess(detect: IntArray)

        //异常
        fun onCameraError(status: Int)
    }

}